package com.opal.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ExcelDownloadUtil {
    public static void ExcelUtil(HttpServletResponse response, Workbook workbook, String ExcelName, HttpServletRequest request) throws IOException {
        request.getSession().removeAttribute("endflag");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(ExcelName.getBytes("utf-8"), "iso8859-1"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        OutputStream os = response.getOutputStream();
        workbook.write(os);
        os.flush();
        os.close();
        request.getSession().setAttribute("endflag", "1");
    }

    //响应回浏览器
    public static void responseData(HttpServletResponse response, HSSFWorkbook h) throws IOException {
        //设置下载头
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        //设置以时间为结尾名字
        SimpleDateFormat newsdf=new SimpleDateFormat("yyyyMMddHHmmss");
        //创建时间
        String date = newsdf.format(new Date());
        response.addHeader("Content-Disposition", "attachment;filename=\""
                + new String(("三联BOM-" + date + ".xls").getBytes("GBK"),
                "ISO8859_1") + "\"");
        OutputStream out = response.getOutputStream();
        h.write(out);
        out.flush();
        out.close();
        h.close();
    }
}
